from urllib import request, parse
import random, json
import hashlib, time


def youdao(keyword):
    u = 'fanyideskweb'
    d = keyword
    f = str(int(time.time() * 1000) + random.randint(1, 10))
    c = 'p09@Bn{h02_BIEe]$P^nG'

    sign = hashlib.md5((u + d + f + c).encode('utf-8')).hexdigest()

    base_url = 'http://fanyi.youdao.com/translate_o?smartresult=dict&smartresult=rule'

    # 构造请求对象
    data = {
        'i': keyword,
        'from': 'AUTO',
        'to': 'AUTO',
        'smartresult': 'dict',
        'client': 'fanyideskweb',
        'salt': f,
        'sign': sign,
        'doctype': 'json',
        'version': '2.1',
        'keyfrom': 'fanyi.web',
        'action': 'FY_BY_REALTIME',
        'typoResult': 'false',
    }
    data = parse.urlencode(data)

    headers = {
        'Cookie':'OUTFOX_SEARCH_USER_ID=1137937692@10.169.0.83; JSESSIONID=aaaEdBfo500XRgh4ORwEw; OUTFOX_SEARCH_USER_ID_NCOO=1390100699.7910304; ___rl__test__cookies=1544426579595',
        'User-Agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36',
        'Referer': 'http://fanyi.youdao.com/'
    }

    req = request.Request(url=base_url, data=bytes(data, encoding='utf-8'), headers=headers)
    res = request.urlopen(req)

    str_json = res.read().decode('utf-8')
    myjson = json.loads(str_json)
    info = myjson['translateResult'][0][0]['tgt']
    details = myjson['smartResult']['entries']
    print(info)
    for d in details:
        print(d,end='')


if __name__ == '__main__':
    while True:
        keyword = input('请输入要翻译的单词： ')
        if keyword == 'q':
            break
        youdao(keyword)
